#include "MessageSubscriber.h"

#include <fastdds/dds/domain/DomainParticipantFactory.hpp>
#include <fastdds/dds/subscriber/qos/DataReaderQos.hpp>
#include <fastdds/rtps/transport/shared_mem/SharedMemTransportDescriptor.h>

using namespace eprosima::fastdds::dds;
using namespace eprosima::fastdds::rtps;
using namespace eprosima::fastrtps::rtps;
bool MessageSubscriber_shm::init(InitParam param)
{
    std::string ptcp_name = "DomainParticipant_pub_shm";
    DomainParticipantQos pqos = PARTICIPANT_QOS_DEFAULT;
    pqos.name(ptcp_name);
    // Explicit configuration of SharedMem transport
    pqos.transport().use_builtin_transports = false;
    auto sm_transport = std::make_shared<SharedMemTransportDescriptor>();
    sm_transport->segment_size(param.segment_size);
    sm_transport->max_message_size(param.max_msg_size);
    pqos.transport().user_transports.push_back(sm_transport);

    auto factory = DomainParticipantFactory::get_instance();
    //participant_ = factory->create_participant_with_profile("DomainParticipant_Sub");
    participant_ = factory->create_participant(param.domain_id, pqos);
    if (!participant_) {
        return false;
    }
    type_.register_type(participant_);

    auto subscriber = participant_->create_subscriber(SUBSCRIBER_QOS_DEFAULT);
    if (!subscriber) {
        return false;
    }
    auto topic = participant_->create_topic(param.topic, "Message", TOPIC_QOS_DEFAULT);
    if (!topic) {
        return false;
    }
    DataReaderQos rqos = DATAREADER_QOS_DEFAULT;
    rqos.history().kind = KEEP_LAST_HISTORY_QOS;
    rqos.history().depth = param.depth;
    rqos.resource_limits().max_samples = param.max_samples;
    rqos.resource_limits().allocated_samples = param.allocated_samples;
    rqos.reliability().kind = RELIABLE_RELIABILITY_QOS;
    rqos.durability().kind = TRANSIENT_LOCAL_DURABILITY_QOS;
    rqos.data_sharing().automatic();
    auto listener = new SubListener;
    auto reader = subscriber->create_datareader(topic, rqos, listener);
    if (!reader) {
        return false;
    }
    listener_ = listener;
    reader_ = reader;
    subscriber_ = subscriber;
    topic_ = topic;
    return true;
}